package com.demo.demo.json;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.everit.json.schema.Schema;
import org.everit.json.schema.loader.SchemaLoader;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;


/**
 * Copyright
 *
 * @Author WuHuang
 * @Date 2023/5/12
 */
public class SchemaToJsonConverter {

    public static void main(String[] args) throws IOException {
        // 读取Schema文件
        InputStream schemaInputStream = SchemaToJsonConverter.class.getResourceAsStream("/schema.json");

        // 将Schema加载为Everit JSON Schema对象
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode schemaJsonNode = objectMapper.readTree(schemaInputStream);
        String schemaJsonString = objectMapper.writeValueAsString(schemaJsonNode);   // 将JsonNode对象转换为字符串
        JSONObject schemaJsonObject = new JSONObject(schemaJsonString);
        JSONArray fields = schemaJsonObject.getJSONArray("fields");

        // 读取Schema文件
        InputStream schemaInputStream2 = SchemaToJsonConverter.class.getResourceAsStream("/schema2.json");

        // 将Schema加载为Everit JSON Schema对象
        JsonNode schemaJsonNode2 = objectMapper.readTree(schemaInputStream2);
        String schemaJsonString2 = objectMapper.writeValueAsString(schemaJsonNode2);   // 将JsonNode对象转换为字符串
        JSONObject schemaJsonObject2 = new JSONObject(schemaJsonString2);

        LinkedHashMap<Object, Object> objectObjectHashMap = new LinkedHashMap<>();
        for (int i = 0; i < fields.length(); i++) {
            JSONObject field = fields.getJSONObject(i);
            String name = field.getString("name");
            if (schemaJsonObject2.has(name)){
                Object o = schemaJsonObject2.get(name);
                objectObjectHashMap.put(name,o);
                continue;
            }
            objectObjectHashMap.put(name,null);
            System.out.println(name);
        }
        // 将Map转换为JSON字符串
        String json = objectMapper.writeValueAsString(objectObjectHashMap);
        System.out.println(json);
        System.out.println(schemaJsonString);
    }
}

